﻿using FCModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FCBLL
{
    public class SAPBOMConvertBLL
    {
        public static string start = "EE";
        /// <summary>
        /// 建立sapBom列表
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static DataSet CreateSAPBOMByxlsx(DataSet ds)
        {
            string[] desc = { "1ST", "2ND" };
            string S2BomCom = "";
            string stHALB = "";
           
            string mainName = "";
            if (!ds.Tables[0].Rows[2][0].ToString().StartsWith("产品编号") && string.IsNullOrWhiteSpace(ds.Tables[0].Rows[2][13].ToString()))
            {
                ds.Tables[0].Rows.RemoveAt(0);
            }
            string name = ds.Tables[0].Rows[2][13].ToString();
            if (name.Contains("："))
            {
                mainName = name.Split('：')[1];
            }
            else if (name.Contains(":"))
            {
                mainName = name.Split(':')[1];
            }
            else {
                throw new Exception("请检查 BOM产品名称 格式是否正确");
            }
            int mainCount = Convert.ToInt32(SAPBOMConvertBLL.getPanelCntByOutPrdName(mainName));

            List<SAPBOMdao> SapBOMS1S2 = getSapS1S2(ds, desc,mainCount, out S2BomCom,out stHALB);
            List<SAPBOMdao> SapBOM_D = getSap_D(ds,mainCount, S2BomCom);
            List<SAPBOMdao> sapBomMain = getMainSapBom(ds);
            List<SAPBOMdao> SapBOMAll = SapBOMS1S2.Union(SapBOM_D).Union(sapBomMain).ToList<SAPBOMdao>();
            
            return CommonBLL.ToDataSet<SAPBOMdao>(SapBOMAll);
        }

      
        /// <summary>
        /// 获取SAPBom最后几行， 
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        protected static List<SAPBOMdao> getMainSapBom(DataSet ds) 
        {
            List<SAPBOMdao> SapBOM = new List<SAPBOMdao>();
            for (int k = 0; k < ds.Tables.Count; k++)
            {
                DataTable dt = ds.Tables[k];
                SAPBOMdao main = new SAPBOMdao();
                main.BOMpartNO = dt.Rows[2][0].ToString().Split('：')[1].Trim();
                main.num = 1;
                main.BOMrojectNO = "0010";
                main.BOMComponent = start + dt.Rows[2][13].ToString().Split('：')[1] + "-D"; ;
                main.ComponentNum = "1";
                SapBOM.Add(main);
            }
            return SapBOM;
        }

        protected static string get40(string longItem,out string result)
        {
            int count = 3000;
            string temp = longItem;
            if (longItem.Length <= count)
            {
                result = longItem.Substring(longItem.Length);
                return longItem;
            }
            else
            {
                longItem = longItem.Substring(0, count);
                result = temp.Substring(count);
                return longItem;
            }
        }
        /// <summary>
        /// 获取SAPBom-D
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        protected static List<SAPBOMdao> getSap_D(DataSet ds,int mainCount, string s2BomCom)
        {
            List<SAPBOMdao> SapBOM = new List<SAPBOMdao>();
            string partNO = start + ds.Tables[0].Rows[2][13].ToString().Split('：')[1] + "-D";
            int prono = 10;
            for (int k = 0; k < ds.Tables.Count; k++)
            {
                DataTable dt = ds.Tables[k];
                int current = Convert.ToInt32(getPanelCntByOutPrdName(dt.Rows[2][13].ToString().Split('：')[1])) / mainCount;
                bool S1begin = false;
                for (int i = 4; i < dt.Rows.Count; i++)
                {
                    if (string.IsNullOrWhiteSpace(dt.Rows[i][8].ToString())) continue;
                    if (dt.Rows[i][13].ToString().ToUpper().Contains("FER"))
                    {
                        S1begin = true;
                        continue;
                    }
                    if (dt.Rows[i][13].ToString().ToUpper().Contains("HALB"))
                    {
                        S1begin = false;
                    }
                    if (S1begin)
                    {
                        SAPBOMdao S1Row = new SAPBOMdao();
                        S1Row.BOMpartNO = partNO;
                        S1Row.num = 1;
                        S1Row.BOMrojectNO = prono.ToString("0000");
                        S1Row.BOMComponent = dt.Rows[i][8].ToString();
                        S1Row.ComponentNum = string.IsNullOrWhiteSpace(dt.Rows[i][9].ToString()) ?
                            "" : (Convert.ToInt32(dt.Rows[i][9].ToString()) * current).ToString();
                        S1Row.ItemType = "";            //项目类别
                        S1Row.ReplaceStrategy = "";     //替代策略
                        S1Row.ReplaceGroup = "";        //替代组
                        S1Row.ReplacePriority = "";     //替代优先级
                        S1Row.Possibility = "";         //使用可能性按 %
                        S1Row.DeliverPlace = "";        //发货地点
                        S1Row.OrderByStr = "";
                        #region
                        string longItem = dt.Rows[i][11].ToString();
                        S1Row.Item1 = get40(longItem, out longItem);
                        S1Row.Item2 = get40(longItem, out longItem);
                        #endregion
                        if (string.IsNullOrWhiteSpace(S1Row.BOMComponent)) continue;
                        prono += 10;
                        SapBOM.Add(S1Row);
                    }
                }

                if (k != 0)
                {
                    SAPBOMdao S1Row = new SAPBOMdao();
                    S1Row.BOMpartNO = partNO;
                    S1Row.num = 1;
                    S1Row.BOMrojectNO = prono.ToString("0000");
                    S1Row.BOMComponent = start + dt.Rows[2][13].ToString().Split('：')[1] + "-D";
                    S1Row.ComponentNum = (Int32.Parse(getPanelCntByOutPrdName(dt.Rows[2][13].ToString().Split('：')[1])) * -1 / mainCount).ToString();//"-1"
                    SapBOM.Add(S1Row);
                }
            }
            SAPBOMdao S2Row = new SAPBOMdao();
            S2Row.BOMpartNO = partNO;
            S2Row.num = 1;
            S2Row.BOMrojectNO = prono.ToString("0000");
            S2Row.BOMComponent = s2BomCom;
            S2Row.ComponentNum = "1";
            SapBOM.Add(S2Row);
            return SapBOM;
        }
        /// <summary>
        /// 获取S1,S2面
        /// </summary>
        /// <param name="ds">xlsx</param>
        /// <param name="descs">s1,s2</param>
        /// <returns></returns>
        protected static List<SAPBOMdao> getSapS1S2(DataSet ds, string[] descs, int mainCount,out string S2partNo, out string stHALB)
        {
            stHALB = "";
            List<SAPBOMdao> SapBOM = new List<SAPBOMdao>();
            string S1partNo = start + ds.Tables[0].Rows[2][13].ToString().Split('：')[1] + "-S1";
            S2partNo = start + ds.Tables[0].Rows[2][13].ToString().Split('：')[1] + "-S2";
            int count = 0;
            foreach (string desc in descs)
            {
                int prono = 10;
                for (int k = 0; k < ds.Tables.Count; k++)
                {
                    DataTable dt = ds.Tables[k];
                    if (dt.TableName == "flowchart") continue;
                    string partNO = "";
                    bool S1begin = false;
                    string outprdno = ds.Tables[k].Rows[2][13].ToString().Split('：')[1];
                    //string outprdno = ds.Tables[k].TableName.Substring(0, ds.Tables[k].TableName.IndexOf('(')).Replace("'","");
                    int outprdnoQty = Convert.ToInt32(SAPBOMConvertBLL.getPanelCntByOutPrdName(outprdno)) / mainCount;
                    if (outprdnoQty != 1)
                    {
                        string s="";
                    }

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i][13].ToString().ToUpper().Contains(desc))
                        {
                            S1begin = true;
                            partNO = dt.Rows[i][8].ToString();

                            if (desc.Contains("1") && k == 0)
                            {
                                stHALB = partNO;
                            }
                            continue;
                        }
                        if (string.IsNullOrWhiteSpace(dt.Rows[i][1].ToString()))
                        {
                            S1begin = false;
                        }
                        if (S1begin)
                        {
                            SAPBOMdao S1Row = new SAPBOMdao();
                            S1Row.BOMpartNO = partNO;
                            S1Row.num = 1;
                            S1Row.BOMrojectNO = dt.Rows[i][2].ToString();
                            S1Row.BOMComponent = dt.Rows[i][8].ToString();
                            S1Row.ComponentNum = (Int32.Parse(dt.Rows[i][9].ToString().Trim()) * outprdnoQty).ToString();
                            S1Row.ItemType = "";            //项目类别
                            S1Row.ReplaceStrategy = "";     //替代策略
                            S1Row.ReplaceGroup = "";        //替代组
                            S1Row.ReplacePriority = "";     //替代优先级
                            S1Row.Possibility = "";         //使用可能性按 %
                            S1Row.DeliverPlace = "";        //发货地点
                            S1Row.OrderByStr = "";
                            #region
                            string longItem = replaceLongItem(dt.Rows[i][11].ToString());
                            S1Row.Item1 =  get40(longItem, out longItem);
                            S1Row.Item2 = get40(longItem, out longItem);
                            #endregion
                            if (string.IsNullOrWhiteSpace(S1Row.BOMComponent)) continue;
                            SapBOM.Add(S1Row);
                        }
                    }
                    if (desc.Contains("1"))
                    {
                        SAPBOMdao S1 = new SAPBOMdao();
                        S1.BOMpartNO = S1partNo;
                        S1.num = 1;
                        S1.BOMrojectNO = prono.ToString("0000");
                        S1.BOMComponent = partNO;
                        S1.ComponentNum = "1";
                        if (string.IsNullOrWhiteSpace(S1.BOMComponent)) continue;
                        SapBOM.Add(S1);
                    }
                    if (desc.Contains("2"))
                    {
                        SAPBOMdao S2 = new SAPBOMdao();
                        S2.BOMpartNO = S2partNo;
                        S2.num = 1;
                        S2.BOMrojectNO = prono.ToString("0000");
                        S2.BOMComponent = partNO;
                        S2.ComponentNum = "1";
                        if (string.IsNullOrWhiteSpace(S2.BOMComponent)) continue;
                        SapBOM.Add(S2);
                    }
                    prono += 10;
                    count = prono;
                }
            }

            SAPBOMdao SRow = new SAPBOMdao();
            SRow.BOMpartNO = S2partNo;
            SRow.num = 1;
            SRow.BOMrojectNO = count.ToString("0000");
            SRow.BOMComponent = S1partNo;
            SRow.ComponentNum = "1";
            SapBOM.Add(SRow);
            return SapBOM;
        }

        public static string getPanelCntByOutPrdName(string OutPrdName)
        {
            var PanelCnt = new BaseRepositoryBLL<bas_Bom_Dnum>()
                .LoadEntities(p => p.OutPrdName.Equals(OutPrdName.Trim())).ToList<bas_Bom_Dnum>();

            if (PanelCnt.Count > 0)
            {
                return Convert.ToInt32(PanelCnt.FirstOrDefault().PanelCnt).ToString();
            }
            else throw new Exception(string.Format(@"找不到{0} BOM负用量，请输入到系统", OutPrdName.Trim()));
        }

        public static string replaceLongItem(string strItem)
        {
            strItem = strItem.Replace(", ", ",").Replace(",,", ",");
            return strItem;
        }
       
    }
}
